package com.yuexi.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuexi.domain.bill.bo.AddBillBO;
import com.yuexi.domain.bill.bo.BillBO;
import com.yuexi.domain.bill.bo.BillQueryBO;
import com.yuexi.domain.repository.BillRepository;
import com.yuexi.domain.util.CalendarUtil;
import com.yuexi.infrastructure.converter.Converter;
import com.yuexi.infrastructure.db.entity.Bill;
import com.yuexi.infrastructure.db.mapper.BillMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author jie
 * @date 2023/4/6 -17:01
 */
@Slf4j
@Repository
public class BillRepositoryImpl extends ServiceImpl<BillMapper, Bill> implements BillRepository {

    @Override
    public List<BillBO> list(BillQueryBO bo) {
        LambdaQueryWrapper<Bill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(bo.getAreaType()), Bill::getAreaType, bo.getAreaType());

        if (null != bo.getCreateTimeFrom()) {
            queryWrapper.ge(Bill::getCreateTime, CalendarUtil.getStartDate(bo.getCreateTimeFrom()));
        }

        if (null != bo.getCreateTimeTo()) {
            queryWrapper.le(Bill::getCreateTime, CalendarUtil.getEndDate(bo.getCreateTimeTo()));
        }

        queryWrapper.orderByDesc(Bill::getCreateTime);
        return Converter.INSTANCE.toBillBOList(super.list(queryWrapper));
    }

    @Override
    public BillBO add(AddBillBO bo) {
        super.save(Converter.INSTANCE.toBill(bo));
        return Converter.INSTANCE.toBillBO(bo);
    }
}
